/**
 * createPlace service node file
 */

var createPlace = function(title, lat, lng, catId, subCatId, createById){
	var self = this;
	self.title = accountId;
	self.lat = followerId;
        self.lng = accountId;
	self.catId = followerId;
        self.subCatId = accountId;
	self.createById = followerId;
	self.success = options.success;
	self.error = options.error;
	self.createPlace();
};

createPlace.prototype._error = function(code, message){
	if(typeof this.error == 'function') {
		this.error(code, message);
	}
};

createPlace.prototype._success = function(data){
	if(typeof this.success == 'function') {
		this.success(data);
	}
};

createPlace.prototype.check = function(nextStatement){
	var self = this;
	if(self.accountId == self.followerId) {
		self._error(9999, 'Account id same Follower id');
		return;
	}
	Mysql.query("SELECT (SELECT COUNT(*) FROM Account WHERE id="+Mysql.escape(self.accountId)+" LIMIT 1) AS c1"
	+",(SELECT COUNT(*) FROM Account WHERE id="+Mysql.escape(self.followerId)+" LIMIT 1) AS c2"
	+",(SELECT COUNT(*) FROM Follow WHERE accountId="+Mysql.escape(self.accountId)+" AND followerId="+Mysql.escape(self.followerId)+" LIMIT 1) AS c3", function(error, results){
		if(error) {
			console.log('Mysql error: '+error);
			self._error(9999, 'Mysql error');
			return;
		}
		var result = results[0];
		if(result.c1 == 0) {
			self._error(9999, 'Account not found');
			return;
		}
		else if(result.c2 == 0) {
			self._error(9999, 'Accoung follower not found');
			return;
		}
		else if(result.c3 != 0) {
			self._error(9999, 'Duplicate follow');
			return;
		}
		nextStatement();
	});
};

createPlace.prototype.createPlace = function(){
	var self = this;
	self.check(function(){
		Mysql.query("INSERT INTO Follow(accountId, followerId) VALUES("+Mysql.escape(self.accountId)+","+Mysql.escape(self.followerId)+")", function(error, result){
			if(error) {
				console.log('Mysql error: '+error);
				self._error(9999, 'Mysql error');
				return;
			}
			self._success({ id: result.insertId, accountId: self.accountId, followerId: self.followerId });
			return;
		});
	});
};

module.exports = createPlace;